import Vue from 'vue'
import Router from 'vue-router'

import { session, STORAGE_KEY } from '@/utils/storage.service';

Vue.use(Router);

/* Layout */
import Layout from '@/layout';

// 公共路由
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/error/404'),
    hidden: true
  },
  {
    path: '/401',
    component: () => import('@/views/error/401'),
    hidden: true
  },
  {
    path: '',
    component: Layout,
    redirect: 'user',
    children: [


      {
        path: "user",
        component: () => import('@/views/user/index'),
        name: "User",
        meta: { title: "用户管理", icon: "dashboard", affix: true },
      },
      {
        path: "model",
        component: () => import('@/views/model/index'),
        name: "Model",
        meta: { title: "模型管理", icon: "dashboard", affix: true },
      },
      {
        path: "video",
        component: () => import('@/views/video/index'),
        name: "Video",
        meta: { title: "视频管理", icon: "dashboard", affix: true },
      },
    ]
  },
]


// 防止连续点击多次路由报错
let routerPush = Router.prototype.push;
let routerReplace = Router.prototype.replace;
// push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(err => err)
}
// replace
Router.prototype.replace = function push(location) {
  return routerReplace.call(this, location).catch(err => err)
}
const router =  new Router({
  mode: 'history', // 去掉url中的#
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

router.beforeEach(async (to, from, next) => {

  if (['/404', '/401'].includes(to.path)) {
    next();
    return;
  }

  if (to.path.slice(0, 6) === '/login') {
    session.remove(STORAGE_KEY.TOKEN);
    next();
    return;
  }
  if (!session.get(STORAGE_KEY.TOKEN)) {
    next('/login');
    return;
  }
  next();
});


export default router;
